package com.chenwang.measure.ui.activity;

import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.chenwang.measure.MyApp;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.ObserverOnNext;
import com.chenwang.measure.model.bean.LocationBean;
import com.chenwang.measure.model.bean.ServerBean;
import com.chenwang.measure.ui.dialog.APNSettingDialog;
import com.chenwang.measure.ui.dialog.SourceDialog;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyCrashHandler;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxTime;
import com.chenwang.measure.utils.RxUtils;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.google.gson.Gson;
import com.rxjava.rxlife.RxLife;

import java.io.IOException;
import java.io.OutputStream;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;

//CORS网络模式
public class CorsActivity extends BaseActivity {


    @BindView(R.id.et_apn)
    EditText mEtApn;         //APN
    @BindView(R.id.et_server)
    EditText mEtServer;    //服务器
    @BindView(R.id.et_ip)
    EditText mEtIp;       //ip
    @BindView(R.id.et_port)
    EditText mEtPort;///端口
    @BindView(R.id.et_source)
    EditText mEtSource;// 源数据
    @BindView(R.id.et_user)
    EditText mEt;//    用户名
    @BindView(R.id.et_password)
    EditText mEtPassword;//密码
    @BindView(R.id.tv_ok)
    TextView mTvOk;//  测试用的
    private String mPasss;
    private String mUser;
    private String mSource;
    private String mPort;
    private String mIp;
    private String mServer;
    private String mApn;
    private RxTime mRxTime;

    @Override
    public int setLayoutId() {
        return R.layout.activity_cors;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initCors();

    }

    //初始化cors配置
    private void initCors() {
        try {
            LocationBean.getInstance().setIs925(true);
            String json = SharePreferenceUtils.getString(this, "cors_last", "");
            if (!TextUtils.isEmpty(json)) {
                Gson gson = new Gson();
                ServerBean serverBean = gson.fromJson(json, ServerBean.class);
                mEtApn.setText(serverBean.getVpn());
                mEtServer.setText(serverBean.getName());
                mEtIp.setText(serverBean.getIp());
                mEtPort.setText(serverBean.getPort());
                mEtSource.setText(serverBean.getSource());
                mEt.setText(serverBean.getUser());
                mEtPassword.setText(serverBean.getPassword());
                if (MyApp.getBluetoothSocket() != null) {
                    MyApp.getBluetoothSocket().getOutputStream().write("set datalink gprs on\r\n".getBytes());//打开gprs


                }
            }

        } catch (IOException e) {
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
            MyLogger.i(e.getMessage());
        }
    }


    @OnClick({R.id.iv_sourcelist,R.id.tv_apn_setting, R.id.tv_add_server, R.id.tv_download, R.id.btn})
    public void onViewClicked(View view) {
        try {

            if (MyApp.getBluetoothSocket() != null) {
                switch (view.getId()) {
                    case R.id.tv_apn_setting://设置apn
                        APNSettingDialog apnSettingDialog = new APNSettingDialog();
                        apnSettingDialog.show(getSupportFragmentManager(), "");
                        break;
                    case R.id.tv_add_server://添加 服务器
                        Intent intent = new Intent(this, ServerAddActivity.class);
                        startActivityForResult(intent, 1);
                        break;
                    case R.id.tv_download://加载源列表

                        break;
                    case R.id.btn://连接cors
                        connect();
                        break;
                    case R.id.iv_sourcelist://加载源数据
                        String apn = mEtApn.getText().toString();
                        String server = mEtServer.getText().toString();
                        String ip = mEtIp.getText().toString();
                        String port = mEtPort.getText().toString();
                        if (TextUtils.isEmpty(apn)) {
                            MyToast.show("apn不能为空");
                        } else if (TextUtils.isEmpty(ip)) {
                            MyToast.show("ip不能为空");
                        } else if (TextUtils.isEmpty(port)) {
                            MyToast.show("端口不能为空");
                        } else {
                            final String param = "set datalink gprs cors param " + apn + " " + ip + " " + port + " TCP Client\r\n";

                            MyApp.getBluetoothSocket().getOutputStream().write(param.getBytes());
                            SourceDialog dialog = new SourceDialog();
                            dialog.setI(new SourceDialog.I() {
                                @Override
                                public void success(String s) {
                                    mEtSource.setText(s);
                                }
                            });
                            dialog.show(getSupportFragmentManager(), "");


                        }
                        break;
                }
            } else {
                MyToast.show("设备未连接");
            }
        }catch (IOException e) {
            MyCrashHandler.newInstance().saveCrashInfoToFile(e);
        }
    }

    //连接cors网络
    private void connect() {
        mApn = mEtApn.getText().toString();
        mServer = mEtServer.getText().toString();
        mIp = mEtIp.getText().toString();
        mPort = mEtPort.getText().toString();
        mSource = mEtSource.getText().toString();
        mUser = mEt.getText().toString();
        mPasss = mEtPassword.getText().toString();
        if (TextUtils.isEmpty(mApn)){
            MyToast.show("apn 不能为空");
        }else if (TextUtils.isEmpty(mIp)){
            MyToast.show("ip不能为空");
        }else  if (TextUtils.isEmpty(mPort)){
            MyToast.show("端口不能为空");
        }else {
            saveLastCors();
            final String param = "set datalink gprs cors param " + mApn + " " + mIp + " " + mPort + " TCP Client\r\n";
            final String accounts = "set datalink gprs cors srctable " + mSource + " " + mUser + " " + mPasss + "\r\n";
            Observable.create(new ObservableOnSubscribe<Boolean>() {
                @Override
                public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                    showLoading("正在连接");
                    OutputStream outStream = MyApp.getBluetoothSocket().getOutputStream();
                    LocationBean.getInstance().setOkMsg(true); //开始解析回令 ok
                    //关闭sbas
                    if (SharePreferenceUtils.getInt(CorsActivity.this, "device_mode", 0)==1){

                        LocationBean.getInstance().setOk(" ");//先将保存ok字符串设为""
                        outStream.write("sbascontrol disable msas\r\n".getBytes());
                        FileUtils.log("关闭SBAS指令：" + "sbascontrol disable msas");
                        Thread.sleep(1000);
                        //如果返回的是 OK！ 表示指令发送成功
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("关闭sbas 1ok");
                        } else {
                            //指令没有解析到回令OK 则不在继续发送指令
                            FileUtils.log("关发送失败 闭SBAS指令：" + "sbascontrol disable msas");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);//false 不在解析OK！
                        }

                        if (LocationBean.getInstance().isOkMsg()) {
                            Thread.sleep(2000);
                            LocationBean.getInstance().setOk(" ");
                            outStream.write("rtkobsmode 0\r\n".getBytes());
                            FileUtils.log("关闭SBAS指令：" + "rtkobsmode 0");
                            Thread.sleep(1000);
                            if (LocationBean.getInstance().getOk().equals("OK!")) {
                                MyLogger.i("关闭sbas 2ok");
                            } else {
                                FileUtils.log("发送失败 关闭SBAS指令：" + "rtkobsmode 0");

                                emitter.onNext(false);
                                emitter.onComplete();
                                LocationBean.getInstance().setOkMsg(false);
                            }

                        }
                    }

                    //关闭电台模式
                    if (SharePreferenceUtils.getInt(CorsActivity.this, "device_mode", 0)==3){
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write("set datalink radio off\r\n".getBytes());
                        FileUtils.log("关闭电台指令：" + "set datalink radio off");
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("关闭电台");
                        } else {
                            FileUtils.log("发送失败 关闭电台指令：" + "set datalink radio off");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);

                        }


                     /*   if (LocationBean.getInstance().isOkMsg()){
                            Thread.sleep(2000);
                            LocationBean.getInstance().setOk(" ");
                            outStream.write("interfacemode com2 compass on\r\n".getBytes());
                            FileUtils.log("关闭电台指令：" + "interfacemode com2 compass on");
                            Thread.sleep(1000);
                            if (LocationBean.getInstance().getOk().equals("OK!")) {
                                MyLogger.i("关闭电台2");

                            } else {
                                FileUtils.log("发送失败 关闭电台指令：" + "interfacemode com2 compass on");
                                emitter.onNext(false);
                                emitter.onComplete();
                                LocationBean.getInstance().setOkMsg(false);
                            }

                        }*/


                    }

                    //cors 指令开始发送
                    if (LocationBean.getInstance().isOkMsg()) { //判断是否开始解析OK！
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write("set datalink gprs on\r\n".getBytes());
                        FileUtils.log("指令：" + "set datalink gprs on");
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("1ok");
                        } else {
                            FileUtils.log("发送失败指令：" + "set datalink gprs on");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);

                        }

                    }

                    if (LocationBean.getInstance().isOkMsg()) {
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write("tst gprsmsg on\r\n".getBytes());
                        FileUtils.log("指令：" + "tst gprsmsg on");
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("2ok");

                        } else {
                            FileUtils.log("发送失败指令：" + "tst gprsmsg on");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);
                        }

                    }

                    if (LocationBean.getInstance().isOkMsg()) {
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write("tst connect com2 gprs\r\n".getBytes());
                        FileUtils.log("指令：" + "tst connect com2 gprs");
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("3ok");
                        } else {
                            FileUtils.log("发送失败指令：" + "tst connect com2 gprs");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);
                        }

                    }


                    if (LocationBean.getInstance().isOkMsg()) {
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write(param.getBytes());
                        FileUtils.log("指令：" + param);
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("4ok");

                        } else {
                            FileUtils.log("发送失败指令：" + param);
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);
                        }

                    }

                    if (LocationBean.getInstance().isOkMsg()) {
                        Thread.sleep(25000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write(accounts.getBytes());
                        FileUtils.log("指令：" + accounts);
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("5 ok");

                        } else {
                            FileUtils.log("发送失败指令：" + accounts);
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);

                        }

                    }
                    if (LocationBean.getInstance().isOkMsg()) {
                        Thread.sleep(2000);
                        LocationBean.getInstance().setOk(" ");
                        outStream.write("interfacemode gprs auto auto on\r\n".getBytes());
                        FileUtils.log("指令：" + "interfacemode gprs auto auto on");
                        Thread.sleep(1000);
                        if (LocationBean.getInstance().getOk().equals("OK!")) {
                            MyLogger.i("6ok");

                        } else {
                            FileUtils.log("发送失败指令：" + "interfacemode gprs auto auto on");
                            emitter.onNext(false);
                            emitter.onComplete();
                            LocationBean.getInstance().setOkMsg(false);
                        }

                    }
                   if (LocationBean.getInstance().isOkMsg()) {
                       outStream.write("saveconfig\r\n".getBytes());
                       FileUtils.log("指令：" + "saveconfig");
                       Thread.sleep(1000);
                       LocationBean.getInstance().setOkMsg(false);
                       for (int i = 0; i < 120; i++) {
                           if (LocationBean.getInstance().getCosr() == 15) {
                               emitter.onNext(true);
                               break;
                           }
                           if (i == 119) {
                               emitter.onNext(false);
                               emitter.onComplete();
                               FileUtils.log("cors启动失败 未解到15状态");


                           }
                           Thread.sleep(1000);
                       }
                   }


                }
            }).compose(RxUtils.<Boolean>io_main())
                    .as(RxLife.as(this))
                    .subscribe(new ObserverOnNext<Boolean>() {
                @Override
                public void onNext(Boolean aBoolean) {
                    if (aBoolean) {
                        SharePreferenceUtils.putInt(CorsActivity.this, "device_mode", 2);
                        MyToast.show("CORS模式设定成功");
                        finish();
                    } else {
                        MyToast.show("CORS模式启动失败 请重试");
                    }

                    dismissLoading();
                }
            });
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocationBean.getInstance().setIs925(false);
        LocationBean.getInstance().setOkMsg(false);

    }

    //保存最近一次配置
    private void saveLastCors(){
        ServerBean serverBean = new ServerBean();
        serverBean.setVpn(mApn);
        serverBean.setName(mServer);
        serverBean.setIp(mIp);
        serverBean.setPort(mPort);
        serverBean.setSource(mSource);
        serverBean.setUser(mUser);
        serverBean.setPassword(mPasss);
        Gson gson = new Gson();
        String json = gson.toJson(serverBean);//保存最后一次配置
        SharePreferenceUtils.putString(CorsActivity.this,"cors_last" , json);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            if (resultCode == 2) {
                //设置的服务器信息
                ServerBean serverBean = data.getParcelableExtra("data");
                mEtServer.setText(serverBean.getName());
                mEtIp.setText(serverBean.getIp());
                mEtPort.setText(serverBean.getPort());
                mEtPassword.setText(serverBean.getPassword());
                mEt.setText(serverBean.getUser());
            }
        }
    }




}
